/**
 * 主题管理器
 * 管理应用主题切换、样式定制和动态主题
 */

/**
 * 预定义主题
 */
const THEMES = {
	light: {
		name: '浅色主题',
		type: 'light',
		colors: {
			// 主色调
			primary: '#007AFF',
			primaryLight: '#5AC8FA',
			primaryDark: '#0051D5',
			
			// 次要色调
			secondary: '#5856D6',
			secondaryLight: '#AF52DE',
			secondaryDark: '#3634A3',
			
			// 成功/错误/警告
			success: '#34C759',
			error: '#FF3B30',
			warning: '#FF9500',
			info: '#5AC8FA',
			
			// 背景色
			background: '#FFFFFF',
			backgroundSecondary: '#F2F2F7',
			backgroundTertiary: '#FFFFFF',
			
			// 表面色
			surface: '#FFFFFF',
			surfaceSecondary: '#F2F2F7',
			surfaceTertiary: '#E5E5EA',
			
			// 文本色
			text: '#000000',
			textSecondary: '#3C3C43',
			textTertiary: '#8E8E93',
			textDisabled: '#C7C7CC',
			
			// 边框色
			border: '#C6C6C8',
			borderLight: '#E5E5EA',
			
			// 分割线
			divider: '#C6C6C8',
			
			// 阴影
			shadow: 'rgba(0, 0, 0, 0.1)',
			shadowLight: 'rgba(0, 0, 0, 0.05)',
			
			// 覆盖层
			overlay: 'rgba(0, 0, 0, 0.4)'
		}
	},
	
	dark: {
		name: '深色主题',
		type: 'dark',
		colors: {
			// 主色调
			primary: '#0A84FF',
			primaryLight: '#64D2FF',
			primaryDark: '#0056CC',
			
			// 次要色调
			secondary: '#5E5CE6',
			secondaryLight: '#BF5AF2',
			secondaryDark: '#3634A3',
			
			// 成功/错误/警告
			success: '#30D158',
			error: '#FF453A',
			warning: '#FF9F0A',
			info: '#64D2FF',
			
			// 背景色
			background: '#000000',
			backgroundSecondary: '#1C1C1E',
			backgroundTertiary: '#2C2C2E',
			
			// 表面色
			surface: '#1C1C1E',
			surfaceSecondary: '#2C2C2E',
			surfaceTertiary: '#3A3A3C',
			
			// 文本色
			text: '#FFFFFF',
			textSecondary: '#EBEBF5',
			textTertiary: '#8E8E93',
			textDisabled: '#48484A',
			
			// 边框色
			border: '#38383A',
			borderLight: '#48484A',
			
			// 分割线
			divider: '#38383A',
			
			// 阴影
			shadow: 'rgba(0, 0, 0, 0.3)',
			shadowLight: 'rgba(0, 0, 0, 0.15)',
			
			// 覆盖层
			overlay: 'rgba(0, 0, 0, 0.6)'
		}
	},
	
	blue: {
		name: '蓝色主题',
		type: 'light',
		colors: {
			primary: '#1976D2',
			primaryLight: '#42A5F5',
			primaryDark: '#0D47A1',
			secondary: '#1565C0',
			secondaryLight: '#42A5F5',
			secondaryDark: '#0D47A1',
			success: '#4CAF50',
			error: '#F44336',
			warning: '#FF9800',
			info: '#2196F3',
			background: '#FAFAFA',
			backgroundSecondary: '#F5F5F5',
			backgroundTertiary: '#FFFFFF',
			surface: '#FFFFFF',
			surfaceSecondary: '#F5F5F5',
			surfaceTertiary: '#EEEEEE',
			text: '#212121',
			textSecondary: '#424242',
			textTertiary: '#757575',
			textDisabled: '#BDBDBD',
			border: '#E0E0E0',
			borderLight: '#F5F5F5',
			divider: '#E0E0E0',
			shadow: 'rgba(25, 118, 210, 0.15)',
			shadowLight: 'rgba(25, 118, 210, 0.08)',
			overlay: 'rgba(25, 118, 210, 0.4)'
		}
	},
	
	green: {
		name: '绿色主题',
		type: 'light',
		colors: {
			primary: '#4CAF50',
			primaryLight: '#81C784',
			primaryDark: '#2E7D32',
			secondary: '#388E3C',
			secondaryLight: '#81C784',
			secondaryDark: '#1B5E20',
			success: '#4CAF50',
			error: '#F44336',
			warning: '#FF9800',
			info: '#2196F3',
			background: '#F1F8E9',
			backgroundSecondary: '#E8F5E8',
			backgroundTertiary: '#FFFFFF',
			surface: '#FFFFFF',
			surfaceSecondary: '#E8F5E8',
			surfaceTertiary: '#C8E6C9',
			text: '#1B5E20',
			textSecondary: '#2E7D32',
			textTertiary: '#4CAF50',
			textDisabled: '#A5D6A7',
			border: '#C8E6C9',
			borderLight: '#E8F5E8',
			divider: '#C8E6C9',
			shadow: 'rgba(76, 175, 80, 0.15)',
			shadowLight: 'rgba(76, 175, 80, 0.08)',
			overlay: 'rgba(76, 175, 80, 0.4)'
		}
	},
	
	purple: {
		name: '紫色主题',
		type: 'light',
		colors: {
			primary: '#9C27B0',
			primaryLight: '#BA68C8',
			primaryDark: '#6A1B9A',
			secondary: '#7B1FA2',
			secondaryLight: '#BA68C8',
			secondaryDark: '#4A148C',
			success: '#4CAF50',
			error: '#F44336',
			warning: '#FF9800',
			info: '#2196F3',
			background: '#F3E5F5',
			backgroundSecondary: '#E1BEE7',
			backgroundTertiary: '#FFFFFF',
			surface: '#FFFFFF',
			surfaceSecondary: '#E1BEE7',
			surfaceTertiary: '#CE93D8',
			text: '#4A148C',
			textSecondary: '#6A1B9A',
			textTertiary: '#9C27B0',
			textDisabled: '#CE93D8',
			border: '#CE93D8',
			borderLight: '#E1BEE7',
			divider: '#CE93D8',
			shadow: 'rgba(156, 39, 176, 0.15)',
			shadowLight: 'rgba(156, 39, 176, 0.08)',
			overlay: 'rgba(156, 39, 176, 0.4)'
		}
	}
}

/**
 * 主题管理器类
 */
class ThemeManager {
	constructor() {
		this.currentTheme = 'light'
		this.customThemes = {}
		this.listeners = []
		this.cssVariables = new Map()
		
		this.init()
	}
	
	/**
	 * 初始化主题管理器
	 */
	init() {
		this.loadSavedTheme()
		this.loadCustomThemes()
		this.applyTheme(this.currentTheme)
		this.setupSystemThemeListener()
	}
	
	/**
	 * 加载保存的主题
	 */
	loadSavedTheme() {
		try {
			if (typeof uni !== 'undefined') {
				const saved = uni.getStorageSync('currentTheme')
				if (saved && (THEMES[saved] || this.customThemes[saved])) {
					this.currentTheme = saved
				}
			}
		} catch (error) {
			console.error('加载主题失败:', error)
		}
	}
	
	/**
	 * 加载自定义主题
	 */
	loadCustomThemes() {
		try {
			if (typeof uni !== 'undefined') {
				const saved = uni.getStorageSync('customThemes')
				if (saved) {
					this.customThemes = saved
				}
			}
		} catch (error) {
			console.error('加载自定义主题失败:', error)
		}
	}
	
	/**
	 * 设置系统主题监听
	 */
	setupSystemThemeListener() {
		// 监听系统主题变化
		if (typeof window !== 'undefined' && window.matchMedia) {
			const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
			darkModeQuery.addListener((e) => {
				if (this.currentTheme === 'auto') {
					this.applyTheme('auto')
				}
			})
		}
	}
	
	/**
	 * 获取所有可用主题
	 * @returns {Object} 主题列表
	 */
	getAvailableThemes() {
		return {
			...THEMES,
			...this.customThemes,
			auto: {
				name: '跟随系统',
				type: 'auto',
				colors: null
			}
		}
	}
	
	/**
	 * 获取当前主题
	 * @returns {string} 当前主题名称
	 */
	getCurrentTheme() {
		return this.currentTheme
	}
	
	/**
	 * 获取当前主题配置
	 * @returns {Object} 主题配置
	 */
	getCurrentThemeConfig() {
		if (this.currentTheme === 'auto') {
			return this.getSystemTheme()
		}
		return THEMES[this.currentTheme] || this.customThemes[this.currentTheme] || THEMES.light
	}
	
	/**
	 * 获取系统主题
	 * @returns {Object} 系统主题配置
	 */
	getSystemTheme() {
		if (typeof window !== 'undefined' && window.matchMedia) {
			const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
			return isDark ? THEMES.dark : THEMES.light
		}
		return THEMES.light
	}
	
	/**
	 * 设置主题
	 * @param {string} themeName - 主题名称
	 * @returns {boolean} 是否设置成功
	 */
	setTheme(themeName) {
		if (themeName === 'auto' || THEMES[themeName] || this.customThemes[themeName]) {
			this.currentTheme = themeName
			this.applyTheme(themeName)
			this.saveCurrentTheme()
			this.notifyListeners(themeName)
			return true
		}
		return false
	}
	
	/**
	 * 应用主题
	 * @param {string} themeName - 主题名称
	 */
	applyTheme(themeName) {
		let themeConfig
		
		if (themeName === 'auto') {
			themeConfig = this.getSystemTheme()
		} else {
			themeConfig = THEMES[themeName] || this.customThemes[themeName] || THEMES.light
		}
		
		// 应用CSS变量
		this.applyCSSVariables(themeConfig.colors)
		
		// 设置状态栏样式
		this.setStatusBarStyle(themeConfig.type)
		
		// 设置导航栏样式
		this.setNavigationBarStyle(themeConfig.colors)
		
		console.log(`应用主题: ${themeConfig.name}`)
	}
	
	/**
	 * 应用CSS变量
	 * @param {Object} colors - 颜色配置
	 */
	applyCSSVariables(colors) {
		if (typeof document !== 'undefined') {
			const root = document.documentElement
			
			Object.entries(colors).forEach(([key, value]) => {
				const cssVar = `--theme-${key.replace(/([A-Z])/g, '-$1').toLowerCase()}`
				root.style.setProperty(cssVar, value)
				this.cssVariables.set(cssVar, value)
			})
		}
	}
	
	/**
	 * 设置状态栏样式
	 * @param {string} type - 主题类型
	 */
	setStatusBarStyle(type) {
		if (typeof uni !== 'undefined') {
			try {
				uni.setNavigationBarColor({
					frontColor: type === 'dark' ? '#ffffff' : '#000000',
					backgroundColor: type === 'dark' ? '#000000' : '#ffffff'
				})
			} catch (error) {
				console.warn('设置状态栏样式失败:', error)
			}
		}
	}
	
	/**
	 * 设置导航栏样式
	 * @param {Object} colors - 颜色配置
	 */
	setNavigationBarStyle(colors) {
		if (typeof uni !== 'undefined') {
			try {
				uni.setNavigationBarColor({
					frontColor: colors.text,
					backgroundColor: colors.background
				})
			} catch (error) {
				console.warn('设置导航栏样式失败:', error)
			}
		}
	}
	
	/**
	 * 创建自定义主题
	 * @param {string} name - 主题名称
	 * @param {Object} config - 主题配置
	 * @returns {boolean} 是否创建成功
	 */
	createCustomTheme(name, config) {
		if (!name || !config || !config.colors) {
			return false
		}
		
		// 验证颜色配置
		const requiredColors = ['primary', 'background', 'text']
		for (const color of requiredColors) {
			if (!config.colors[color]) {
				console.error(`自定义主题缺少必需颜色: ${color}`)
				return false
			}
		}
		
		// 合并默认配置
		const defaultTheme = THEMES.light
		const customTheme = {
			name: config.name || name,
			type: config.type || 'light',
			colors: {
				...defaultTheme.colors,
				...config.colors
			}
		}
		
		this.customThemes[name] = customTheme
		this.saveCustomThemes()
		
		console.log(`创建自定义主题: ${name}`)
		return true
	}
	
	/**
	 * 删除自定义主题
	 * @param {string} name - 主题名称
	 * @returns {boolean} 是否删除成功
	 */
	deleteCustomTheme(name) {
		if (!this.customThemes[name]) {
			return false
		}
		
		// 如果当前使用的是要删除的主题，切换到默认主题
		if (this.currentTheme === name) {
			this.setTheme('light')
		}
		
		delete this.customThemes[name]
		this.saveCustomThemes()
		
		console.log(`删除自定义主题: ${name}`)
		return true
	}
	
	/**
	 * 获取颜色值
	 * @param {string} colorName - 颜色名称
	 * @returns {string} 颜色值
	 */
	getColor(colorName) {
		const themeConfig = this.getCurrentThemeConfig()
		return themeConfig.colors[colorName] || '#000000'
	}
	
	/**
	 * 获取CSS变量名
	 * @param {string} colorName - 颜色名称
	 * @returns {string} CSS变量名
	 */
	getCSSVariable(colorName) {
		return `--theme-${colorName.replace(/([A-Z])/g, '-$1').toLowerCase()}`
	}
	
	/**
	 * 切换深色/浅色主题
	 */
	toggleDarkMode() {
		const currentConfig = this.getCurrentThemeConfig()
		if (currentConfig.type === 'dark') {
			this.setTheme('light')
		} else {
			this.setTheme('dark')
		}
	}
	
	/**
	 * 是否为深色主题
	 * @returns {boolean} 是否为深色主题
	 */
	isDarkMode() {
		const currentConfig = this.getCurrentThemeConfig()
		return currentConfig.type === 'dark'
	}
	
	/**
	 * 添加主题变化监听器
	 * @param {Function} listener - 监听器函数
	 */
	addListener(listener) {
		if (typeof listener === 'function') {
			this.listeners.push(listener)
		}
	}
	
	/**
	 * 移除主题变化监听器
	 * @param {Function} listener - 监听器函数
	 */
	removeListener(listener) {
		const index = this.listeners.indexOf(listener)
		if (index > -1) {
			this.listeners.splice(index, 1)
		}
	}
	
	/**
	 * 通知监听器
	 * @param {string} themeName - 主题名称
	 */
	notifyListeners(themeName) {
		const themeConfig = this.getCurrentThemeConfig()
		this.listeners.forEach(listener => {
			try {
				listener(themeName, themeConfig)
			} catch (error) {
				console.error('主题监听器执行失败:', error)
			}
		})
	}
	
	/**
	 * 保存当前主题
	 */
	saveCurrentTheme() {
		try {
			if (typeof uni !== 'undefined') {
				uni.setStorageSync('currentTheme', this.currentTheme)
			}
		} catch (error) {
			console.error('保存主题失败:', error)
		}
	}
	
	/**
	 * 保存自定义主题
	 */
	saveCustomThemes() {
		try {
			if (typeof uni !== 'undefined') {
				uni.setStorageSync('customThemes', this.customThemes)
			}
		} catch (error) {
			console.error('保存自定义主题失败:', error)
		}
	}
	
	/**
	 * 导出主题配置
	 * @returns {Object} 主题配置
	 */
	exportThemes() {
		return {
			currentTheme: this.currentTheme,
			customThemes: this.customThemes,
			exportTime: new Date().toISOString()
		}
	}
	
	/**
	 * 导入主题配置
	 * @param {Object} data - 主题数据
	 * @returns {boolean} 是否导入成功
	 */
	importThemes(data) {
		try {
			if (data.customThemes) {
				this.customThemes = { ...this.customThemes, ...data.customThemes }
				this.saveCustomThemes()
			}
			
			if (data.currentTheme && (THEMES[data.currentTheme] || this.customThemes[data.currentTheme])) {
				this.setTheme(data.currentTheme)
			}
			
			console.log('主题配置导入成功')
			return true
		} catch (error) {
			console.error('导入主题配置失败:', error)
			return false
		}
	}
	
	/**
	 * 重置主题设置
	 */
	resetThemes() {
		this.currentTheme = 'light'
		this.customThemes = {}
		this.applyTheme('light')
		this.saveCurrentTheme()
		this.saveCustomThemes()
		this.notifyListeners('light')
		console.log('主题设置已重置')
	}
	
	/**
	 * 生成主题预览
	 * @param {string} themeName - 主题名称
	 * @returns {Object} 预览数据
	 */
	generatePreview(themeName) {
		const theme = THEMES[themeName] || this.customThemes[themeName]
		if (!theme) {
			return null
		}
		
		return {
			name: theme.name,
			type: theme.type,
			colors: {
				primary: theme.colors.primary,
				background: theme.colors.background,
				text: theme.colors.text,
				surface: theme.colors.surface
			}
		}
	}
}

// 创建全局实例
const themeManager = new ThemeManager()

// 便捷方法
export const setTheme = (themeName) => {
	return themeManager.setTheme(themeName)
}

export const getCurrentTheme = () => {
	return themeManager.getCurrentTheme()
}

export const getCurrentThemeConfig = () => {
	return themeManager.getCurrentThemeConfig()
}

export const getColor = (colorName) => {
	return themeManager.getColor(colorName)
}

export const getCSSVariable = (colorName) => {
	return themeManager.getCSSVariable(colorName)
}

export const toggleDarkMode = () => {
	themeManager.toggleDarkMode()
}

export const isDarkMode = () => {
	return themeManager.isDarkMode()
}

export const getAvailableThemes = () => {
	return themeManager.getAvailableThemes()
}

export const createCustomTheme = (name, config) => {
	return themeManager.createCustomTheme(name, config)
}

export const deleteCustomTheme = (name) => {
	return themeManager.deleteCustomTheme(name)
}

export const addThemeListener = (listener) => {
	themeManager.addListener(listener)
}

export const removeThemeListener = (listener) => {
	themeManager.removeListener(listener)
}

export const exportThemes = () => {
	return themeManager.exportThemes()
}

export const importThemes = (data) => {
	return themeManager.importThemes(data)
}

export const resetThemes = () => {
	themeManager.resetThemes()
}

export const generateThemePreview = (themeName) => {
	return themeManager.generatePreview(themeName)
}

// 导出主题常量
export { THEMES }

// 导出管理器实例
export default themeManager